package priv.xakml.java.springboot2demo.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import priv.xakml.java.springboot2demo.domain.Test;
import priv.xakml.java.springboot2demo.domain.TestItem;
import priv.xakml.java.springboot2demo.mapper.ITestItemMapper;
import priv.xakml.java.springboot2demo.mapper.ITestMapper;
import priv.xakml.java.springboot2demo.service.ITestService;

import javax.swing.*;
import java.util.List;

@Service
public class TestService implements ITestService {

    @Autowired
    private ITestMapper testMapper;

    @Autowired
    private ITestItemMapper testItemMapper;

    public TestService(ITestMapper testMapper) {
        this.testMapper = testMapper;
    }

    @Override
    @Cacheable(value = "",key = "")
    public Test getTestById(long id) {
       return this.testMapper.getById(id);
    }

    @Override
    public boolean updateBatch(List<Test> list) {
        int rowsAffect = this.testMapper.updateCurrentPoints(list);
        return  rowsAffect> 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean Insert(Test obj) throws Exception {
       int rowAffect = this.testMapper.insertTest(obj);
       if(rowAffect > 0){
           if(obj.getItems() != null && obj.getItems().size() > 0){
                for (TestItem item : obj.getItems()){
                    item.setTestId(obj.getId());
                    rowAffect = this.testItemMapper.insertTestItem(item);
                    if(rowAffect <= 0){
                        throw new Exception("明细保存失败");
                    }
                    if (item.getTestName().equals("B")){
                        throw new Exception("not allowed to save B");
                    }
                }
           }
           return true;
       }
       return false;
    }
}
